<?php
/*
   worldquery.php
   query "world" database, "select" command only
   method: POST
   content-type: application/x-www-form-urlencoded
   request: SQL select single-field query statement only
   response: resultset in JSON *** changed from XML to JSON by Tyler 3.16.09
   author: Modified by Tom A.
   created: march-03-09
*/

if(isset($_POST))
{
	//echo '<b>You sent query:</b> <font color="blue">'.$_POST['q'].'</font><br/><br/>';//DEBUG
	$querystr=trim($_POST['q']);
	if($querystr=='')
            exit('<error>You sent an empty query.</error>');
	$token=preg_split("/[\s,]+/",$querystr);
        
        require('dbconnector.php');
        $db=opendb();
       
        if(strcasecmp($token[0],'select') == 0){
            
            $myquery=mysql_query(stripslashes($querystr));
            if($myquery){
		
                $response="{\n\"rides\" : [\n";
		while($row=mysql_fetch_array($myquery,MYSQL_ASSOC)){
						$response.="{ \n";
                        $response.="\t\"id\": \"{$row[$token[1]]}\",\n";
						$response.="\t\"title\": \"{$row[$token[2]]}\",\n";
                        $response.= "\t\"city\": \"{$row[$token[3]]}\",\n";
                        $response.= "\t\"start_point\": \"{$row[$token[4]]}\",\n";                       
                        $response.= "\t\"date\": \"{$row[$token[5]]}\",\n";
                        $response.= "\t\"time\": \"{$row[$token[6]]}\",\n";
                        $response.= "\t\"leader\": \"{$row[$token[7]]}\",\n";
                        $response.= "\t\"leader_phone\": \"{$row[$token[8]]}\",\n";
                        $response.= "\t\"description\": \"".str_replace( "\n", "<br />", $row[$token[9]] )."\",\n";     // convert input \n to <br />, otherwise it breaks JSON file.
                        $response.= "\t\"category\": \"{$row[$token[10]]}\",\n";
                        $response.= "\t\"hilliness\": \"{$row[$token[11]]}\",\n";
                        $response.= "\t\"mileage\": \"{$row[$token[12]]}\"\n";
                        $response.="},\n";
                    
                     // "day" row removed 3.16.09 by tyler
                }
		$response.="]\n}";
        
		echo $response;
		mysql_free_result($myquery);
            }
            else echo '<error>Could not run query: <font color="red">'.mysql_error().'</font></error>';//DEBUG
        }
        else if(strcasecmp($token[0],'insert') == 0){
                if (mysql_query(stripslashes($querystr)))
                     {echo "Record Inserted.";}
                else {echo "Error Inserting.";}
           }
}
else echo '<error>Server did not receive a request.</error>';
?>
